/* eslint-disable eqeqeq */
/* eslint-disable react/jsx-handler-names */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './index.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form, Row, Col, message, Popconfirm } from 'antd';
import { IconC, SelectC, InputNumberC } from '../../../components';
import dictData from './config';
import AddFenzi from './addFenzi';
import _ from 'lodash';

class AssetIndexC extends PureComponent {
  state = {
    visible: false, // 分子分母是否可见
    indexItem: undefined, // 分子分母的详情数据
    indexPosition: undefined, // 类型 是新增分子还是分母
    warnList: [],
    addType: undefined, // 1新增 2编辑
  };

  formRef = React.createRef();

  componentDidMount() {
    this.props.onRef(this);
    this.formatwarnList(); // 触警操作列表
  }

  // 编辑分子分母
  editfzfm = (obj, type) => {
    this.setState({
      indexPosition: type,
    });
    if (!obj) {
      // 新增
      this.setState({
        visible: true,
        addType: 1,
      });
    } else {
      // 编辑
      this.setState({
        visible: true,
        indexItem: _.cloneDeep(obj),
        addType: 2,
      });
    }
  };

  // 点击删除  前端删除 保存之后给后端 才能生效
  onDeleteItem = (id) => {
    const riskIndexs = this.props.detailData?.riskIndexs || [];
    const arr = riskIndexs.filter((item) => item.indexId != id);
    this.props.changeDetailData(arr); // 通知父级修改riskIndexs
  };

  fenziRender = (data, type) => {
    return (
      <div className={myStyle.fenziWrapper}>
        <div className={myStyle.fenziItem}>
          {data.length ? (
            <div className={myStyle.fenzihasData}>
              {data.map((item, index) => {
                return (
                  <div key={index}>
                    {index == 0 && item.indexSymbol == 2 ? <div>0</div> : null}
                    <div className={myStyle.fuhaoItem}>{item.indexSymbol == 1 ? (index == 0 ? '' : '+') : '-'}</div>
                    <div className={myStyle.indexName} title={item.indexName}>
                      {item.indexName}
                    </div>
                    <div className={myStyle.fenzioprate}>
                      <IconC
                        isHover={false} // 鼠标悬停是否更换图标
                        type={'edit'}
                        title='编辑'
                        hoverAfter={true}
                        onClick={(e) => {
                          this.editfzfm(item, type);
                        }}
                      />

                      <Popconfirm
                        title={'确定删除？'}
                        icon={<ExclamationCircleOutlined />}
                        onConfirm={() => {
                          this.onDeleteItem(item.indexId);
                        }}
                      >
                        <IconC
                          isHover={false} // 鼠标悬停是否更换图标
                          type={'delete'}
                          title='删除'
                          hoverAfter={true}
                        />
                      </Popconfirm>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className={myStyle.noData}>
              <span>{type == '1' ? '请输入分子' : '请输入分母'}</span>
            </div>
          )}
        </div>
        <div className={myStyle.addFenzi}>
          <IconC
            style={{ width: '14px', height: '14px' }}
            isHover={false} // 鼠标悬停是否更换图标
            type={'newly'}
            title='新增'
            onClick={() => this.editfzfm(undefined, type)}
          />
        </div>
      </div>
    );
  };

  // 分子点击取消
  onCancel = () => {
    this.setState({
      visible: false,
      indexItem: undefined,
    });
  };

  // 分子点击确定
  onOK = (row) => {
    const riskIndexs = this.props.detailData?.riskIndexs || [];
    const arr = _.cloneDeep(riskIndexs);
    console.log(riskIndexs);
    if (this.state.addType == 2) {
      // 编辑
      for (let index = 0; index < riskIndexs.length; index++) {
        const item = riskIndexs[index];
        if (item.indexId === row.indexId) {
          arr.splice(index, 1, row); // 替换修改的那个分子
        }
      }
      this.props.changeDetailData(arr); // 通知列表页的组件里详情record修改
    } else {
      // 新增
      console.log(row, '点击分子确定');
      riskIndexs.push(row);
      this.props.changeDetailData(riskIndexs); // 通知列表页的组件里详情record修改
    }
    this.setState({
      visible: false,
      indexItem: undefined,
    });
  };

  // 触警操作列表 调整格式进行展示
  formatwarnList = () => {
    const { detailData } = this.props;
    const arr = [];
    if (JSON.stringify(detailData) != '{}') {
      const { pecentView } = detailData;
      if (detailData.warningThreshold !== null && detailData.prohibitedThreshold !== null) {
        // 预警和禁止都有
        arr.push({
          valveValue1: pecentView ? detailData.warningThreshold * 100 : detailData.warningThreshold,
          valveType1: '1',
          keys: ['valveValue1', 'valveType1'],
        });
        arr.push({
          valveValue2: pecentView ? detailData.prohibitedThreshold * 100 : detailData.prohibitedThreshold,
          valveType2: '3',
          keys: ['valveValue2', 'valveType2'],
        });
      } else {
        arr.push({
          valveValue1:
            detailData.warningThreshold !== null
              ? pecentView
                ? detailData.warningThreshold * 100
                : detailData.warningThreshold
              : pecentView
              ? detailData.prohibitedThreshold * 100
              : detailData.prohibitedThreshold,
          valveType1: detailData.warningThreshold !== null ? '1' : '3',
          keys: ['valveValue1', 'valveType1'],
        });
      }
    } else {
      arr.push({ keys: ['valveValue1', 'valveType1'] });
    }
    this.setState({ warnList: [...arr] });
  };

  // 删除触警
  delWarn = (data) => {
    const { warnList } = this.state;
    const arr = warnList.filter((item) => {
      return JSON.stringify(data.keys) != JSON.stringify(item.keys);
    });
    this.setState({ warnList: [...arr] });
  };

  // 新增触警
  addWarn = () => {
    const { warnList } = this.state;
    warnList.push({ keys: ['valveValue2', 'valveType2'] });
    this.setState({ warnList: [...warnList] });
  };

  // 提交代码
  submit = async () => {
    const { detailData = {} } = this.props;
    let query;
    const values = await this.formRef.current.validateFields();
    console.log('资产指标', values);
    if (values) {
      if (values.valveType1 == values.valveType2) {
        message.error('触警操作不可重复');
        return;
      }
      if (!detailData.riskIndexs) {
        message.error('分子必须填写');
        return;
      } else {
        const fenziList = detailData.riskIndexs.filter((item) => item.indexPosition == 1); // 分子1
        // const fenmuList = detailData.riskIndexs.filter(item => item.indexPosition == 2);//分母2
        if (!fenziList.length) {
          message.error('分子必须填写');
          return;
        }
      }
      // 是百分比的时候 改成原值传递给后端
      const pecentView = values.pecentView == '1';
      if (values.valveType1 == '1') {
        // 警告

        values.warningThreshold = pecentView ? Number(values.valveValue1) / 100 : values.valveValue1;
        delete values.valveType1;
        delete values.valveValue1;
      }
      if (values.valveType1 == '3') {
        // 禁止
        values.prohibitedThreshold = pecentView ? Number(values.valveValue1) / 100 : values.valveValue1;
        delete values.valveType1;
        delete values.valveValue1;
      }
      if (values.valveType2 == '1') {
        // 警告
        values.warningThreshold = pecentView ? Number(values.valveValue2) / 100 : values.valveValue2;
        delete values.valveType2;
        delete values.valveValue2;
      }
      if (values.valveType2 == '3') {
        // 禁止
        values.prohibitedThreshold = pecentView ? Number(values.valveValue2) / 100 : values.valveValue2;
        delete values.valveType2;
        delete values.valveValue2;
      }
      const riskIndexs = _.cloneDeep(detailData.riskIndexs || []);
      riskIndexs.map((item, index) => {
        item.indexSeq = index;
      });

      values.absControlFlag = values.absControlFlag == '1';
      query = {
        ...values,
        riskIndexs: riskIndexs || [],
      };
    }
    return query;
  };

  render() {
    const { detailData = {} } = this.props;
    const { warnList } = this.state;
    const riskIndexs = detailData.riskIndexs || [];
    const fenziList = riskIndexs.filter((item) => item.indexPosition == 1); // 分子1
    const fenmuList = riskIndexs.filter((item) => item.indexPosition == 2); // 分母2

    return (
      <div className='maat-form-father'>
        <Form ref={this.formRef}>
          <Row>
            <Col span={6}>
              <SelectC
                form={this.formRef.current}
                dataIndex='absControlFlag'
                title='绝对值控制'
                initialValue={detailData.absControlFlag === true ? '1' : '2'}
                dataSource={dictData.falseOrTrue}
                rules={[{ required: true, message: '请选择绝对值控制' }]}
              />
            </Col>
          </Row>
          <div className={myStyle.formula}>
            <span>计算公式:</span>
            <div>
              <div className={myStyle.leftItem}>
                <div className={myStyle.title}>公式</div>
                <div className={myStyle.gongshi}>
                  <div>
                    <div className={myStyle.fenzi}>
                      {this.fenziRender(fenziList, '1')}
                      {this.fenziRender(fenmuList, '2')}
                    </div>
                  </div>
                </div>
              </div>
              <div className={myStyle.centerItem}>
                <div className={myStyle.title}>比较方向</div>
                <div>
                  <SelectC
                    form={this.formRef.current}
                    dataIndex={'compareMethod'}
                    showSearch={false}
                    initialValue={detailData.compareMethod ? detailData.compareMethod.toString() : '1'}
                    dataSource={dictData.directionList}
                    rules={[{ required: true, message: '必填' }]}
                    selectWidth={'60px'}
                  />
                </div>
              </div>
              <div className={myStyle.rightItem}>
                <div className={myStyle.rightItemTitle}>
                  <div>
                    <span>控制值</span>
                    <span>触警操作</span>
                  </div>
                </div>
                <div className={myStyle.oprate}>
                  {warnList.map((item, key) => {
                    return (
                      <div key={key}>
                        <div className={key == 0 ? myStyle.controlVal : myStyle.controlVal1}>
                          <InputNumberC
                            form={this.formRef.current}
                            dataIndex={item.keys[0]}
                            precision={4}
                            initialValue={item[item.keys[0]]}
                            rules={[{ required: true, message: '请填写控制值' }]}
                          />
                          {key == 0 && (
                            <div>
                              <SelectC
                                form={this.formRef.current}
                                dataIndex='pecentView'
                                title=''
                                showSearch={false}
                                initialValue={detailData.pecentView == null || detailData.pecentView == undefined ? '2' : detailData.pecentView == true ? '1' : '2'}
                                dataSource={dictData.pecentView}
                                selectWidth={'60px'}
                              />
                            </div>
                          )}
                        </div>
                        <div>
                          <SelectC
                            form={this.formRef.current}
                            dataIndex={item.keys[1]}
                            initialValue={item[item.keys[1]]}
                            dataSource={dictData.warnList}
                            rules={[{ required: true, message: '请选择触警操作' }]}
                          />
                        </div>
                        {key != 0 && (
                          <span className={myStyle.delBtn}>
                            <IconC
                              isHover={false} // 鼠标悬停是否更换图标
                              type={'delete'}
                              title='删除'
                              hoverAfter={true}
                              onClick={(e) => {
                                this.delWarn(item);
                              }}
                            />
                          </span>
                        )}
                      </div>
                    );
                  })}
                </div>
                {warnList.length < dictData.warnList.length && (
                  <div className={myStyle.addBtn}>
                    <IconC
                      isHover={false} // 鼠标悬停是否更换图标
                      type={'newly'}
                      title='新增'
                      onClick={this.addWarn}
                    />
                  </div>
                )}
              </div>
            </div>
          </div>
        </Form>

        {this.state.visible && (
          <AddFenzi onCancel={this.onCancel} onOK={this.onOK} visible={this.state.visible} indexPosition={this.state.indexPosition} detailData={this.state.indexItem} />
        )}
      </div>
    );
  }
}
export default connect(({ limitSetting, dictionaryM, userM: user, loading }) => ({
  limitSetting,
  dictionaryM,
  user,
  loading,
}))(AssetIndexC);
